package com.houdoudou.supplier;

import java.util.Map;

import org.apache.commons.collections.functors.TransformerPredicate;

import com.houdoudou.supplier.bean.Supplier;
import com.houdoudou.supplier.bean.TransPasswordUtil;
import com.houdoudou.supplier.common.CommonFunction;
import com.houdoudou.supplier.common.Constant;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {
	
	

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}


	TextView  hint;
	EditText  telnum,secret;
	View.OnClickListener  myClickListener;
    Button btn_confirm,btn_modifynet;
   
    ProgressBar progress_bar;
    CheckBox remember;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_login);
		init_listener();	
		telnum= (EditText) findViewById(R.id.user_phone_num_act_log);
		secret= (EditText) findViewById(R.id.user_password_act_login);
		btn_confirm=(Button) findViewById(R.id.button_act_login);
		btn_confirm.setOnClickListener(myClickListener);
		btn_modifynet=(Button) findViewById(R.id.btn_modifynet_act_login);
		btn_modifynet.setOnClickListener(myClickListener);
		hint= (TextView) findViewById(R.id.hint_act_login);
		progress_bar= (ProgressBar) findViewById(R.id.progressBar1_act_log);
		remember= (CheckBox) findViewById(R.id.ck_rember_act_login);
		app_configure();
	
		
	}


	
	private void init_listener(){
		
		
		myClickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(v==btn_confirm){
				if(check_input()){														
				
				
					
						 String[] params= new String[3];
		    	           params[0]=Constant.BaseUrl+Constant.SupplierUrl;
		                   params[1]="login";
		                   JSONObject jsonData=new JSONObject();	                   
		   				try {	   					
		   					jsonData.put(Supplier.TELNUM, telnum.getText().toString().trim());
		   					String cipertext=TransPasswordUtil.encrypt(secret.getText().toString().trim());
		   					jsonData.put(Supplier.SECRET, cipertext );
		   					
		   				} catch (Exception e1) {
		   					// TODO Auto-generated catch block
		   					e1.printStackTrace();
		   				}
		   			
		    	         params[2]=jsonData.toString();
		   			  // params[2]="测试中文乱码";
	   				//	JSONObject jo=JSONObject.fromObject(supplier);
		   			//	params[2]=jo.toString();
						new HttpPostTaskforLogin().execute(params);
						btn_confirm.setEnabled(false);
						progress_bar.setVisibility(View.VISIBLE);				
				} //if
				}else if(v==btn_modifynet){
					
				Intent intent= new Intent(LoginActivity.this, NetConfigActivity.class);    	   
				     startActivity(intent);
				}
				
				
				
			} //onClick
		};
		
	}
private boolean check_input( ){
	boolean check1=true,check2 = true,check3 = true;
	
	
	
	if(this.telnum.getText().toString().isEmpty()) {  check2=false; Toast.makeText(getApplicationContext(), "密码不能为空，请输入", Toast.LENGTH_SHORT).show(); }
	if(this.telnum.getText().toString().length()!=11) {  check2=false; Toast.makeText(getApplicationContext(), "号码位数不对，请输入", Toast.LENGTH_SHORT).show();}
	if(this.secret.getText().toString().isEmpty()) { check3=false; Toast.makeText(getApplicationContext(), "名称不能为空，请输入", Toast.LENGTH_SHORT).show(); }
	
	return check1&&check2&&check3;	
       }
class HttpPostTaskforLogin extends android.os.AsyncTask<String,String,Map<String,Object>>{

	

	@Override
	protected Map<String,Object> doInBackground(String... params) {
		// TODO Auto-generated method stub
		  Map<String,Object> map =	CommonFunction.UniversalHttpPost(params);		             
		return map;
	}
	
	@Override
	protected void onPostExecute(Map<String,Object> map) {
		// TODO Auto-generated method stub
	  //	super.onPostExecute(result);
		btn_confirm.setEnabled(true);
		progress_bar.setVisibility(View.INVISIBLE);
		boolean networkstate=(Boolean) map.get("PostState");
		if(!networkstate){
			  hint.setText("提示:网络故障或者网络配置有误，无法连接到服务器");
		       hint.setVisibility(View.VISIBLE); return;
		}
		
		
	    String PostResult=(String) map.get("PostResult");
	    Boolean ActionStatus=false;
		String ErrorInfo="";
		JSONObject json= JSONObject.fromObject(PostResult);
	
		 ActionStatus=json.getBoolean("success");
		 ErrorInfo=json.getString("errorInfo");	
		 hint.setText("提示:"+ErrorInfo);
	       hint.setText("提示:"+ErrorInfo);
	       hint.setVisibility(View.VISIBLE);
	       if(ActionStatus){
	    	  
	    	//   Constant.Current_Supplier_Telnum=telnum.getText().toString();
	    	//   Constant.Current_Supplier_Secret=secret.getText().toString();
	    	 //  Constant.Belong_Owner_Telnum=json.getString("Owner_Telnum");	
	    	   Constant.supplierJO=json.getJSONObject("supplier");	    	  
	    	   SharedPreferences sharedPreferences = LoginActivity.this.getSharedPreferences("config", Context.MODE_PRIVATE);
	    	   Editor editor = sharedPreferences.edit();   
	    	   if(remember.isChecked()){   
	    		   System.out.println("++++++++");
	    	 //  editor.putString("Current_Supplier_Telnum",  Constant.Current_Supplier_Telnum);
	    	  //  editor.putString("Current_Supplier_Secret",  Constant.Current_Supplier_Secret);
	    	   editor.putString("supplier",Constant.supplierJO.toString());
	    	   editor.putBoolean("isRemember",  true);
	    	   editor.commit();    	   
	    	   }
	    	   
	    	   Intent intent= new Intent(LoginActivity.this, SupplierMainActivity.class);    	   
                 startActivity(intent);
                  LoginActivity.this.finish();
                    
	       } // ifActionStatus
	

      } //onpost
       } //httptask
    private void app_configure(){
	  SharedPreferences sharedPreferences = this.getSharedPreferences("config", Context.MODE_PRIVATE);
	  Editor editor = sharedPreferences.edit();   
     
     
       boolean isFirst = sharedPreferences.getBoolean("isFirst", true);
       boolean base_empty=false,owner_empty=false;
      if(sharedPreferences.getString("BaseUrl", "").isEmpty()) base_empty=true;
       if(sharedPreferences.getString("SupplierUrl", "").isEmpty()) owner_empty=true;
       if(isFirst){
    	  
    	   editor.putBoolean("isFirst", false);
    	  
       }
       if(base_empty||owner_empty){
    	   editor.putString("BaseUrl", "http://192.168.1.115"); 
    	   editor.putString("SupplierUrl", ":8080/houdoudou/supplier4App");
       }
       editor.commit(); 
       //可能上次提交未更新 重定义。
       SharedPreferences sp2 = this.getSharedPreferences("config", Context.MODE_PRIVATE);
       Constant.BaseUrl=sp2.getString("BaseUrl", "");
       Constant.SupplierUrl=sp2.getString("SupplierUrl", ""); 
    
       
	    boolean isRember = sp2.getBoolean("isRemember", false);    
	         
	    if (isRember)    
	    {    
	    	if(!sp2.getString("supplier", "").isEmpty()){
	    		Constant.supplierJO= JSONObject.fromObject(sp2.getString("supplier", ""));
	    		telnum.setText(Constant.supplierJO.getString(Supplier.TELNUM));
	    		 secret.setText(Constant.supplierJO.getString(Supplier.SECRET));
	    		 
	    		 String[] params= new String[3];
  	           params[0]=Constant.BaseUrl+Constant.SupplierUrl;
                 params[1]="login";          
  	           params[2]=Constant.supplierJO.toString();		  
				new HttpPostTaskforLogin().execute(params);
				btn_confirm.setEnabled(false);
				progress_bar.setVisibility(View.VISIBLE);	
	    	}
	    	
	    	
	     /*    if(!sp2.getString("Current_Supplier_Telnum", "").isEmpty()) {
	        	 if(!sp2.getString("Current_Supplier_Secret", "").isEmpty()){
	        		
	        		 telnum.setText(sp2.getString("Current_Supplier_Telnum", ""));
	        		 secret.setText(sp2.getString("Current_Supplier_Secret", ""));
	        		  btn_confirm.performClick();
	        		
	        	 }
	         } */
	       	        
	    }
	    
	
	   
   }
	
	
	
}
